package web;

import Utils.web.BaseServlet;
import Utils.web.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;

/**
 * @author d11yu
 */
@WebServlet(name = "CookieServlet", value = "/CookieServlet")
public class CookieServlet extends BaseServlet {
    protected void createCookie(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Cookie cookie = new Cookie("k1", "v1");
        // 通知客户端保存cookie
        response.addCookie(cookie);
        response.getWriter().write("Cookie创建成功！");
    }

    protected void getCookies(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            response.getWriter().write(MessageFormat.format("Cookie[{0}={1}] <br>", cookie.getName(), cookie.getValue()));
        }
    }

    protected void setCookie(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 方案一
        /*Cookie cookie = new Cookie("k1", "v2");
        response.addCookie(cookie);*/

        // 方案二
        Cookie cookie = WebUtils.findCookie("k1", request);
        cookie.setValue("v3");
        response.addCookie(cookie);
    }

    protected void defaultLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = new Cookie("kd", "vd");
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
    }

    protected void deleteNow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = WebUtils.findCookie("kd", request);
        if (cookie != null) {
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
    }

    protected void live3600(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = new Cookie("live3600", "live3600");
        cookie.setMaxAge(3600);
        response.addCookie(cookie);
    }
    
    protected void testPath(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = new Cookie("path", "path");
        cookie.setPath(request.getContextPath()+"/abc");
        response.addCookie(cookie);
        response.getWriter().write("创建了path");
    }
}
